# coding: utf-8
import os
from flask import send_from_directory
from datetime import datetime, timedelta
from flask import Flask
from flask import request, url_for, redirect
from flask import render_template

from views.todos import todos_view
from views.agm import agm_view
from views.agmadmin import agmadmin_view
from views.agmbeta import agmbeta_view, agmbeta_view_en
from views.agmsell import agmsell_view
from views.wechatpay import app as wechatpay_view
from views.agmpay import app as agmpay_view
from views.agmstaff import app as agmstaff_view

from tools import logging

app = Flask(__name__)


# 动态路由
app.register_blueprint(wechatpay_view, url_prefix='/wechatpay')
app.register_blueprint(todos_view, url_prefix='/todos')
# app.register_blueprint(agm_view, url_prefix='/agmbak')
app.register_blueprint(agmbeta_view)
app.register_blueprint(agmbeta_view_en)
app.register_blueprint(agmpay_view, url_prefix='/agmpay')
app.register_blueprint(agmstaff_view, url_prefix='/agmstaff')
# app.register_blueprint(agmbeta_view, url_prefix='/agm')
# app.register_blueprint(agmbetatemp, url_prefix='/')
app.register_blueprint(agmsell_view, url_prefix='/agmsell')
app.register_blueprint(agmadmin_view, url_prefix='/agmadmin')

# @app.route('/')
# def index():
    # return redirect(url_for('agmbeta.index'))
    
@app.route('/agm/')
@app.route('/agm/<path>')
@logging.log
@logging.agmlog
def agmtoindex(path=""):
    if request.query_string:
        path += '?' + request.query_string
    return redirect(url_for('agmbeta.index') + path, 301)

    
@app.route('/imfun', methods=['POST', 'GET'])
def imfun():
    if request.method == 'GET':
        import time, random, string
        timestamp = int(time.time())
        cure_url = request.url
        from tools.wechatAPI import getjstoken, APPID
        ticket = getjstoken()
        # noncestr = 'imfunimfunimfun'
        noncestr = ''.join(random.choice(string.ascii_letters + string.digits) 
            for _ in range(15))
        vars = {
            'noncestr': noncestr, 
            'jsapi_ticket': ticket, 
            'timestamp': str(timestamp), 
            'url': cure_url,
        }    
        sign = sginwechat(vars)
        
        return render_template('imfun.html', 
            timestamp=timestamp, noncestr=noncestr, sign=sign, appid=APPID)
    elif request.method == 'POST':
        if request.args.get('action') == 'uploadimages' and request.data:
            from leancloud import Object, File
            from tools.wechatAPI import getimagedata
            from StringIO import StringIO
            import re
            images = request.data.split(',')
            uploadedlist = []
            for image in images:
                ret = getimagedata(image)
                try:
                    filename = re.search('filename="(.+?)"', ret.headers.get('Content-disposition')).group(1)
                except:
                    filename = image
                imagedata = StringIO(ret.read())
                file = File(filename, imagedata)
                file.save()
                img = Object.extend('WechatUploadImage')()
                img.set('meidaid', image)
                img.set('file', file)
                img.save()
                uploadedlist.append(file.url)
            return ', '.join(uploadedlist)
        if request.data:
            # print request.data
            return '%s' % request.data
        return 'imfunPOST!'
    
def sginwechat(vars):
    import urllib
    from hashlib import sha1
    data = vars.items()
    data.sort(key=lambda x: x[0])
    # print data
    data = '&'.join(['='.join(t) for t in data])
    # print data
    return sha1(data).hexdigest()
    
@app.route('/test', methods=['POST', 'GET'])
@logging.log
def test():
    from views.test import get
    return get()
    
@app.route('/wechat', methods=['POST', 'GET'])
@logging.log
def wechat():
    from views.wechat import get, post
    if request.method == 'GET':
        return get()
    if request.method == 'POST':
        return post()

@app.route('/time')
def time():
    return str(datetime.now()) 
    
@app.route('/googled02fede66bdb03d8.html')
def googlevalid():
    return 'google-site-verification: googled02fede66bdb03d8.html'    
    
@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')
    
@app.route('/MP_verify_lND445HaFFTEhNDe.txt')
def wechat_valid():
    return 'lND445HaFFTEhNDe'    
    
app.secret_key = 'imfunimfun'
app.permanent_session_lifetime = timedelta(days=1)
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 60*60*24*30

# flask asset
from flask_assets import Environment
assets = Environment(app)
assets.url_expire = True
assets.versions = 'timestamp'
assets.manifest = False
assets.cache = False

# ------flask_asset_cache use--------#
# assets.manifest = 'file:flask_asset_cache'
# assets.cache = False
#------------End flask_asset_cache use----#

#if not os.environ.get('VIRTUAL_ENV', '').startswith('F:'):
if not os.environ.get('LC_LOCAL', 'True'):
    assets.auto_build = False
else:
    assets.auto_build = True

# assets.debug = True
